package top.sdwu_top.kbase.util.file.impl;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import top.sdwu_top.kbase.common.aspect.exception.MyException;
import top.sdwu_top.kbase.common.constants.Constants;
import top.sdwu_top.kbase.entity.FileData;
import top.sdwu_top.kbase.util.file.FileUtil;
import top.sdwu_top.kbase.util.file.condition.DefaultCondition;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.UUID;


@Slf4j
@Data
@Component
@Conditional({DefaultCondition.class})
@ConfigurationProperties(prefix = "kbase.local")
public class LocalStorageFileUtil implements FileUtil{

    private String path = "/upload/";

    @Override
    public FileData saveFile(MultipartFile file) {
        FileData fileData = new FileData();
        if (file.isEmpty()) {
            throw new MyException(50003, "无法保存");
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = file.getOriginalFilename();
        String[] fileNameList = fileName.split("\\.");
        String postfix = "";
        if (fileNameList.length > 1) {
            postfix = fileNameList[fileNameList.length-1];
        }
        fileData.setFileType(Constants.getFileType(postfix));
        String filePath = path + uuid + "." + postfix;
        fileData.setFilePath(filePath);
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("保存成功");
            return fileData;
        } catch (IOException e) {
            e.printStackTrace();
            log.info("保存失败");
            throw new MyException(50003, "保存失败");
        }
    }

    @Override
    public FileData saveText(String content, String type) {
        FileData fileData = new FileData();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName= this.path + uuid + "." + type;
        fileData.setFilePath(fileName);
        fileData.setFileType(type);
        try {
            FileWriter writer=new FileWriter(fileName);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileData;
    }

    @Override
    public InputStream getFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        try {
            InputStream inputStream = new FileInputStream(file);
            return inputStream;
        } catch (FileNotFoundException e) {
            return null;
        }
    }

    @Override
    public String getStoreType() {
        return "local";
    }


    @PostConstruct
    private void fixPath() {
        //处理操作系统兼容
        this.path = this.path.replace("/", File.separator);
        this.path = this.path.replace("\\", File.separator);
        if (isLinux() && !StringUtils.startsWith(this.path, File.separator)) {
            this.path = File.separator + this.path;
        }
        if (!isLinux()) {
            if (!StringUtils.contains(this.path, ":")) {
                String sysPath = System.getProperty("user.dir");
                this.path = sysPath + this.path;
            }
        }
        log.info(this.path);
        if (!StringUtils.endsWith(this.path, File.separator)) {
            this.path = this.path + File.separator;
        }
    }

    private boolean isLinux() {
        String os = System.getProperty("os.name");
        if (os != null && os.toLowerCase().contains("linux")) {
            return true;
        } else {
            return false;
        }
    }



}
